﻿using Microsoft.AspNetCore.Mvc;
using System.Diagnostics.CodeAnalysis;
using WebApiExtend;
using Newtonsoft.Json;
using WebApi.Model;

namespace WebApi.Filters
{
    /// <summary>
    /// 登录验证过滤器
    /// </summary>
    public class LoginFilter : AuthorizationFilter
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userid"></param>
        /// <param name="username"></param>
        public override bool CheckToken(string token)
        {
            //需要穿透逻辑
            var flag = false;
            var arr = token.Split(',');

            system_user user = new system_user();
            if (LoginCache.Dict.ContainsKey(Convert.ToInt32(arr[0])))
            {
                user = LoginCache.Dict[Convert.ToInt32(arr[0])];
                if (user.login_token_exp > DateTime.Now && user.login_token == token)
                {
                    flag = true;
                }
            }

            if (!flag)//穿透查询数据库
            {
                user = new SqlClient<system_user>().Where(ex => ex.login_token == token && ex.login_token_exp > DateTime.Now).FirstOrDefault();
                if (user != null)
                {
                    LoginCache.Dict.AddOrUpdate(user.id, user, (key, oldValue) => user);
                    flag = true;
                }
            }
            if (flag)
            {
                _httpContext.Session.SetString("userid", user.id.ToString());
                _httpContext.Session.SetString("username", user.user_name);
                _httpContext.Session.SetString("User", JsonConvert.SerializeObject(user));
            }
            return flag; 
        }
    }
}
